<template>
  <div class="layoutCon">
    <help-header :tab="1"></help-header>
    <div class="breadcrumb">
        <router-link class="home" to="/"></router-link> > <router-link to="/help">취업도우미</router-link> > 워크위즈후기
    </div>
    <div class="frmBox">
      <el-form :model="frm" :rules="rules" ref="helpFrm">
      <ul>
        <li>
          <el-form-item prop="title">
            <el-input v-model="frm.title" placeholder="*제목"></el-input>
          </el-form-item>
        </li>
        <li>
          <el-form-item :error="errors.upload" prop="image_id">
            <el-row>
              <el-col :xs="17" :md="10" class="fileInp">
                <input type="hidden" v-model="frm.image_id">
                <input type="file" title="" ref="fileInput" class="file" @change="changeFile">
                <el-input v-model="fileName" accept="image/jpeg,image/jpg,image/png" placeholder="*메인 썸네일 이미지 첨부하기 (.jpg, jpeg, png)"></el-input>
              </el-col>
              <el-col :xs="7" :md="3">
                <el-button :loading="uploading" class="btn ml" @click="changeFileByInput">첨부하기</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </li>
        <li>
          <el-form-item prop="cont">
            <summernote @checkCon="checkCon"></summernote>
          </el-form-item>
        </li>
        <li class="btns">
          <el-button :loading="isLoading" type="primary" @click="submitForm">작성완료</el-button>
          <el-button class="btn" @click="escFrm">작성취소</el-button>
        </li>
      </ul>
      </el-form>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from "vuex";
import { addJobHelp, uploadImg } from '@/api';
import Summernote from '@/components/summernote'
import helpHeader from '@/components/helpHeader'

export default {
  name:'',
  components:{helpHeader,Summernote},
  props:[],
  data(){
    return {
      uploading:false,
      isLoading:false,
      frm:{
        title:'',        
        cont:'',
        image_id:''
      },
      rules:{
        title: [
          { required: true, message: '제목을 작성해 주세요.', trigger: 'blur' }
        ],
        image_id: [
          { required: true, message: '이미지를 첨부해 주세요.', trigger: 'change' }
        ],
        cont: [
          { required: true, message: '내용을 작성해 주세요.', trigger: 'blur' }
        ],          
      },
      errors:{
        upload:'',
      },
      file:null,
      fileName:'',      
    }
  },
  computed:{
    ...mapState(['token'])
  },
  created(){},
  mounted(){},
  methods:{
    submitForm() {
        this.frm.cont=$('#summernote').summernote('code');
        this.$refs['helpFrm'].validate( async (valid,error) => {
          if (valid) {
            let res = await addJobHelp(this.frm);
            this.isLoading = true;
            if (res.code == 200) {
              this.$alert('성공적으로 제출되었습니다.', '알림', {
                confirmButtonText: '확인',
                callback: action => {
                  this.back();
                }
              });
              this.isLoading = false;
            }else{
              this.isLoading = false;
            }
          } else {
            return false;
          }
        });
    },
    escFrm(){
      this.$confirm('취소 하시면, 기존에 작성된 내용이 모두 삭제됩니다.', '작성취소', {
        confirmButtonText: '확인',
        cancelButtonText: '취소',
      }).then(() => {
        this.back();
      });
    },
    back(){
      this.$router.back()
    },
    changeFileByInput(){
      this.$refs.fileInput.click()
    },
    changeFile(){
      let inputDOM = this.$refs.fileInput;
      let files = inputDOM.files;
       if(files && files[0]) {
         let size = Math.floor(files[0].size / 1024);
          if (size > 5*1024) {
            this.$alert('5MB이하의 이미지를 첨부해주세요.', '알림', {
              confirmButtonText: '확인'
            });
            return false
          }
          this.file = files[0];
          this.fileName=this.file.name;
          this.uploadImg();
       }
    },
    async uploadImg(){
      if(this.file==null){
        this.errors.upload='이미지를 첨부해 주세요.'
      }else{
        try {
          this.uploading=true;
          let res = await uploadImg({image:this.file});
          if (res.code == 200) {
            this.frm.image_id=res.data.id;
            // this.$message({
            //   message: '이미지추가성공',
            //   type: 'success'
            // });
            this.$refs.helpFrm.validateField('image_id');
            this.uploading=false;
            this.errors.upload=''
          }else{
            this.uploading=false;
          }
        } catch (error) {
          this.uploading=false;
          this.errors.upload='이미지 첨부 실패하였습니다.'
        }        
      }
    },
    checkCon(){
      this.frm.cont=$('#summernote').summernote('code');
      this.$refs.helpFrm.validateField('cont');
    }
  },
  watch:{}
}
</script>
<style lang="scss" scoped>
  @import "@/assets/styles/help.scss";
</style>